package com.xiyi.shouxin.init;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.DelayQueue;

import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import com.xiyi.shouxin.entity.admin.Admin;
import com.xiyi.shouxin.entity.user.User;

/*
 * 延时队列实现简单缓存工具
 * 缓存操作人信息和会话凭证
 */
@Component
public class CacheUtil {
    private final ThreadLocal<Admin> adminOperator = new ThreadLocal<>();
    private final Map<String, Admin> tokenAdminMap = new ConcurrentHashMap<>();
    private DelayQueue<DelayTask> delayQueue = new DelayQueue<>();
    private final ThreadLocal<User> userOperator=new ThreadLocal<>();
    private final Map<String,User> tokenUserMap=new ConcurrentHashMap<>();

    private final Map<String,String> phoneCodeMap=new ConcurrentHashMap<>();
    

    public void setAdminOperator(@NonNull Admin admin) {
        adminOperator.set(admin);
    }

    public Admin getAdminOperator() {
        return adminOperator.get();
    }

    public void removeAdminOperator() {
        adminOperator.remove();
    }

    public void putTokenAdmin(@NonNull String token, @NonNull Admin admin) {
        tokenAdminMap.put(token, admin);
    }

    public void removeTokenAdmin(@NonNull String token) {
        tokenAdminMap.remove(token);
    }

    public Admin getAdmin(@NonNull String token) {
        return tokenAdminMap.get(token);
    }

    public DelayTask takeDelayTask() throws InterruptedException {
        return delayQueue.take();
    }

    public void offerDelayTask(DelayTask task) {
        delayQueue.offer(task);
    }

    public void setUserOperator(@NonNull User user) {
        userOperator.set(user);
    }

    public User getUserOperator() {
        return userOperator.get();
    }

    public void removeUserOperator() {
        userOperator.remove();
    }

    public void putTokenUser(@NonNull String token, @NonNull User user) {
        tokenUserMap.put(token, user);
    }

    public void removeTokenUser(@NonNull String token) {
        tokenUserMap.remove(token);
    }

    public User getUser(@NonNull String token) {
        return tokenUserMap.get(token);
    }

    public void putPhoneCode(@NonNull String phone, @NonNull String code) {
        phoneCodeMap.put(phone, code);
    }

    public void removePhoneCode(@NonNull String phone) {
        phoneCodeMap.remove(phone);
    }

    public String getPhoneCode(@NonNull String phone) {
        return phoneCodeMap.get(phone);
    }

}
